package cmpe451.group7.ourcity.util;

import java.io.IOException;

import org.apache.commons.lang3.tuple.Pair;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.jayway.jsonpath.JsonPath;

public class ReverseGeoLocation {

	public static void main(String[] args) {
		Pair<String, String> pair = findByLatLng(41.08545, 29.04450);
		System.out.printf("City: %s - Country : %s\n", pair.getLeft(),
				pair.getRight());
	}

	public static Pair<String, String> findByLatLng(double lat, double lng) {
		try {
			JSONObject response = sendGeoLocationRequest(lat, lng);
			String cityName = JsonPath.read(response,
					"$.results[0].address_components[3].long_name").toString();
			String countryName = JsonPath.read(response,
					"$.results[0].address_components[5].long_name").toString();

			return Pair.of(cityName, countryName);
		} catch (IOException | ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static JSONObject sendGeoLocationRequest(double lat, double lng)
			throws IOException, ParseException {
		HttpTransport httpTransport = new NetHttpTransport();
		HttpRequestFactory requestFactory = httpTransport
				.createRequestFactory();

		// prepare url
		GenericUrl url = new GenericUrl(
				"https://maps.googleapis.com/maps/api/geocode/json");
		url.put("latlng", String.format("%f,%f", lat, lng));
		url.put("sensor", "false");
		url.put("language", "en");

		// send the request
		HttpRequest request = requestFactory.buildGetRequest(url);
		HttpResponse httpResponse = request.execute();

		// parse the response as json object
		JSONParser parser = new JSONParser();
		JSONObject response = (JSONObject) parser.parse(httpResponse
				.parseAsString());

		return response;
	}
}
